﻿using System;

namespace Sencha.Serialization.Bson.Serializers
{
	public class BsonObjectIdSerializer : TypeSerializer<BsonObjectId>
	{
		public override BsonObjectId Deserialize(IJsonReader reader)
		{
			if (reader == null)
				throw new ArgumentNullException("reader");

			if (reader is IBsonReader)
				return this.DeserializeBson(reader as IBsonReader);

			reader.ReadObjectBegin();
			var idString = reader.ReadMember<string>("$oid");
			reader.ReadObjectEnd(false);

			var value = BsonObjectId.Parse(idString);
			return value;
		}
		private BsonObjectId DeserializeBson(IBsonReader reader)
		{
			if (reader.Token != BsonToken.ObjectId)
				throw new Exceptions.UnexpectedBsonToken(reader, BsonToken.ObjectId);

			var objectId = (BsonObjectId)reader.RawValue;
			return objectId;
		}
		public override void Serialize(IJsonWriter writer, BsonObjectId value)
		{
			if (writer == null)
				throw new ArgumentNullException("writer");

			if (writer is IBsonWriter)
			{
				this.SerializeBson(writer as IBsonWriter, value);
				return;
			}

			writer.WriteObjectBegin();
			writer.WriteMember<string>("$oid", value.ToString());
			writer.WriteObjectEnd();
		}
		private void SerializeBson(IBsonWriter writer, BsonObjectId value)
		{
			writer.Write(BsonToken.ObjectId, value);
		}
	}
}
